using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace GeoFramework.Examples
{
    public partial class SynchronizingTheClockForm : Form
    {
        public SynchronizingTheClockForm()
        {
            InitializeComponent();

            // Start listening for GPS data
            GpsDevice.Start();

        }

        private void ComputerClock_ValueChanged(object sender, DateTimeEventArgs e)
        {
            ComputerTimeLabel.Text = e.DateTime.ToLongTimeString();
        }

        private void GpsClock_ValueChanged(object sender, DateTimeEventArgs e)
        {
            GpsTimeLabel.Text = e.DateTime.ToLongTimeString();
            ComputerTimeLabel.Text = DateTime.Now.ToLongTimeString();

            // The GPS-derived date and time can actually be inaccurate until
            // a satellite fix is acquired.  As a result, wait until a fix is present
            // before comparing the computer clock with the GPS clock.

            if (GpsDevice.IsFixed)
            {
                // Calculate the difference between local time and satellite-derived time
                double TimeDifference = e.DateTime.Subtract(DateTime.Now).TotalMilliseconds;

                // Is the local clock slow, fast, or precisely accurate?                
                if (TimeDifference > 0)
                    TimeDifferenceLabel.Text = "Computer clock is " + TimeDifference.ToString() + " milliseconds slow.";
                else if (TimeDifference < 0)
                    TimeDifferenceLabel.Text = "Computer clock is " + Math.Abs(TimeDifference).ToString() + " milliseconds fast.";
                else
                    TimeDifferenceLabel.Text = "Computer clock exactly matches GPS clock.";
            }
            else
            {
                // No fix is present yet
                TimeDifferenceLabel.Text = "Waiting for satellite fix...";
            }
        }

        private void SynchronizeCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            // Enable or disable GPS.NET's clock synchronization features
            GeoFramework.IO.Devices.IsClockSynchronizationEnabled = SynchronizeCheckBox.Checked;
        }
    }
}